import { REACT_TEXT } from "./constant";

export function shallowEqual(obj1, obj2){
  if(obj1 === obj2){
    return true;
  }
  if(typeof obj1 !== 'object' || obj1 === null || typeof obj2 !== 'object' || obj2 === null) {
    return false;
  }
  const keys1 = Object.keys(obj1);
  const keys2 = Object.keys(obj2);
  if(keys1.length !== keys2.length){
    return false;
  }
  for(let key of keys1){
    if(!obj2.hasOwnProperty(key) || obj1[key] !== obj2[key]){
      return false
    }
  }
  return true;
}
/**
 * 判断一个值是不是未定义，也就是null或者undefined
 * @param {*} value 
 * @returns 布尔值
 */
export function isUndefined(val){
  return  val === undefined || val === null;
}

/**
 * 判断一个值是不是定义的，
 * @param {*} val 
 * @returns 
 */
export  function isDefined(val){
  return val !== undefined && val !== null;
}

/**
 * 为了更加语义化，方便后dom diff，把文本节点包装成虚拟DOM
 * @param {*} element 
 * @returns 
 */
export  function wrapToVdom(element){
  return typeof element === "string" || typeof element === "number" ? {
    type: REACT_TEXT,
    props: element
  } : element;
}
/**
 * 
 * @param {*} val 
 * @returns 
 */
export function wrapToArray(val){
  return Array.isArray(val)?val.flat(): [val];
}

export const UserAPI = {
  list(){
    let usersStr = localStorage.getItem('users');
    let users = usersStr?JSON.parse(usersStr):[];
    return users;
  },
  add(user){
    let users = UserAPI.list();
    users.push(user);
    localStorage.setItem('users', JSON.stringify(users));
  },
  find(id){
    let users = UserAPI.list();
    return users.find(user => user.id == id);
  }

}